var map
var showLabels = false
var showDesig = true
var svcSelected = []
var included = []
var limited = []
var excluded = []
var loadFuncId = 0
var hospitalCont
var lastStyle

var placeLayer
var hospitalLayer1
var hospitalLayer2

var places = []

function initMap() {

    showLabelWidth = $('#show-label').width() + 5
    showLabelWidth = "calc(100% - " + String(showLabelWidth) + "px)"
    $('#show-label').css('left', showLabelWidth)

    showLabelWidth = $('#show-legend').width() + 5
    showLabelWidth = "calc(100% - " + String(showLabelWidth) + "px)"
    $('#show-legend').css('left', showLabelWidth)

    $('[name="show-label"]').click(function () {
        if (this.checked) {
            showLabels = true
        } else {
            showLabels = false
        }
        hospitalLayer2.redraw()
        hospitalLayer1.redraw()
    })

    $('[name="show-legend"]').click(function () {
        if (this.checked) {
            $('#hospital-legend').show()
        } else {
            $('#hospital-legend').hide()
        }
    })

    tianditu_sat_3857 = L.tileLayer('http://{s}.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILECOL={x}&TILEROW={y}&tk=c77ff55fbeec6f05de4685b93f816b9a', {
        // zoomOffset: 1,
        subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7']
    })

    tianditu_map_3857 = L.tileLayer('http://{s}.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILECOL={x}&TILEROW={y}&tk=c77ff55fbeec6f05de4685b93f816b9a', {
        subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7']
    })

    tianditu_ter_3857 = L.tileLayer('http://{s}.tianditu.gov.cn/ter_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=ter&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILECOL={x}&TILEROW={y}&tk=c77ff55fbeec6f05de4685b93f816b9a', {
        subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7']
    })

    tianditu_ibo_3857 = L.tileLayer('http://{s}.tianditu.gov.cn/ibo_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=ibo&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILECOL={x}&TILEROW={y}&tk=c77ff55fbeec6f05de4685b93f816b9a', {
        subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7']
    })

    tianditu_cva_3857 = L.tileLayer('http://{s}.tianditu.gov.cn/cva_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILECOL={x}&TILEROW={y}&tk=c77ff55fbeec6f05de4685b93f816b9a', {
        subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7']
    })
    // geoq_styled = L.tileLayer.chinaProvider('Geoq.Normal.PurplishBlue', {});

    var map1 = L.map('map', {
        attributionControl: false,
        crs: L.CRS.EPSG3857,
        layers: [tianditu_map_3857, tianditu_cva_3857],
        minZoom: 1,
        maxZoom: 18,
        worldCopyJump: true,
        maxBounds: [[180, -1800], [-180, 1800]],
        zoomSnap: 0.25,
        zoomDelta: 0.25
    })
    map1.setView([30.6, 114.6], 9)

    var baseMaps = {
        "天地图行政区划图": tianditu_map_3857,
        "天地图卫星图": tianditu_sat_3857,
    }

    var markerOverlays = {
        "地名注记（经纬度投影）": tianditu_cva_3857
    }

    $('.leaflet-top.leaflet-left .leaflet-control-zoom.leaflet-control').remove()

    L.control.layers(baseMaps, markerOverlays).addTo(map1);

    // var zoomControl = L.control.zoom({
    //     position: 'topright'
    // });

    // map1.addControl(zoomControl);
    $('.leaflet-top.leaflet-right .leaflet-control-zoom.leaflet-bar.leaflet-control').css('margin-top', '12px').css('margin-right', '12px')

    return map1
}

function openIntro() {
    if ($("#introText").css("display") == "none") {
        $('#introText').show()
        $('#intro').text('关闭简介')
    } else {
        $('#introText').hide()
        $('#intro').text('关于此地图')
    }
}
function acknowledged() {
    if ($("#announcement").css("display") == "none") {
        $('#announcement').show()
        $('#acknowledged').text('已知悉，关闭')
    } else {
        $('#announcement').hide()
        $('#acknowledged').hide()
    }
}

function removeFromCanvas(canvasOverlay, info) {
    var ctx = info.canvas.getContext('2d');
    ctx.clearRect(0, 0, info.canvas.width, info.canvas.height);
}
function loadHospitals1(canvasOverlay, info) {
    // if (!hospitals) return
    console.log('drawing hospital func 111 called')
    zoomNow = map.getZoom()
    var ctx = info.canvas.getContext('2d');
    ctx.clearRect(0, 0, info.canvas.width, info.canvas.height);
    // if 

    for (i = 0; i < included.length; i++) {
        lat = parseFloat(included[i]['lat8'])
        lng = parseFloat(included[i]['lng8'])
        // console.log(included[i])
        name = included[i]['hospitalName']
        if (info.bounds.contains([lat, lng])) {
            dot = canvasOverlay._map.latLngToContainerPoint([lat, lng]);
            dotX = dot.x; dotY = dot.y
            // if (ct == clickedSeq) { thisIcon = hospitalIconRescue; console.log(addr) } else { thisIcon = hospitalIconFever }
            // ctx.drawImage(thisIcon, dotX - 10, dotY - 10, 20, 20)
            ctx.beginPath();

            ctx.arc(dot.x, dot.y, 7, 0, Math.PI * 2);
            ctx.strokeStyle = '#284'
            ctx.lineWidth = 2
            ctx.stroke()

            ctx.arc(dot.x, dot.y, 6, 0, Math.PI * 2);
            ctx.fillStyle = '#2f5'
            ctx.fill();

            if (zoomNow >= 12) {
                ctx.font = 'bold 14px serif';
                ctx.fillStyle = '#2d5'
                ctx.fillText(name, dot.x + 10, dot.y + 5)
            }
            ctx.closePath();
        }
    }
    for (i = 0; i < limited.length; i++) {
        lat = parseFloat(limited[i]['lat8'])
        lng = parseFloat(limited[i]['lng8'])
        name = limited[i]['hospitalName']

        if (info.bounds.contains([lat, lng])) {
            dot = canvasOverlay._map.latLngToContainerPoint([lat, lng]);
            dotX = dot.x; dotY = dot.y
            // if (ct == clickedSeq) { thisIcon = hospitalIconRescue; console.log(addr) } else { thisIcon = hospitalIconFever }
            // ctx.drawImage(thisIcon, dotX - 10, dotY - 10, 20, 20)
            ctx.beginPath();

            ctx.arc(dot.x, dot.y, 7, 0, Math.PI * 2);
            ctx.strokeStyle = '#e10'
            ctx.lineWidth = 2
            ctx.stroke()

            ctx.arc(dot.x, dot.y, 6, 0, Math.PI * 2);
            ctx.fillStyle = '#e81'
            ctx.fill();

            if (zoomNow >= 12) {
                ctx.font = 'bold 14px serif';
                ctx.fillStyle = '#fc3'
                ctx.fillText(name, dot.x + 10, dot.y + 5)
            }

            ctx.closePath();
        }
    }
    // for (i = 0; i < excluded.length; i++) {
    //     lat = parseFloat(excluded[i]['lat8'])
    //     lng = parseFloat(excluded[i]['lng8'])
    //     name = excluded[i]['hospitalName']

    //     if (info.bounds.contains([lat, lng])) {
    //         dot = canvasOverlay._map.latLngToContainerPoint([lat, lng]);
    //         dotX = dot.x; dotY = dot.y
    //         // if (ct == clickedSeq) { thisIcon = hospitalIconRescue; console.log(addr) } else { thisIcon = hospitalIconFever }
    //         // ctx.drawImage(thisIcon, dotX - 10, dotY - 10, 20, 20)
    //         ctx.beginPath();

    //         ctx.arc(dot.x, dot.y, 7, 0, Math.PI * 2);
    //         ctx.strokeStyle = '#333'
    //         ctx.lineWidth = 2
    //         ctx.stroke()

    //         ctx.arc(dot.x, dot.y, 6, 0, Math.PI * 2);
    //         ctx.fillStyle = '#777'
    //         ctx.fill();

    //         if (showLabels) {
    //             ctx.font = 'bold 14px serif';
    //             ctx.fillStyle = '#bbb'
    //             ctx.fillText(name, dot.x + 10, dot.y + 5)
    //         }

    //         ctx.closePath();
    //     }
    // }
}
function loadHospitals2(canvasOverlay, info) {
    // if (!hospitals) return
    console.log('drawing hospital 222 func called')
    zoomNow = map.getZoom()
    var ctx = info.canvas.getContext('2d');
    ctx.clearRect(0, 0, info.canvas.width, info.canvas.height);

    for (i = 0; i < included2.length; i++) {
        lat = parseFloat(included2[i]['lat'])
        lng = parseFloat(included2[i]['lng'])
        name = included2[i]['name_fmt']

        if (info.bounds.contains([lat, lng])) {
            dot = canvasOverlay._map.latLngToContainerPoint([lat, lng]);
            dotX = dot.x; dotY = dot.y
            // if (ct == clickedSeq) { thisIcon = hospitalIconRescue; console.log(addr) } else { thisIcon = hospitalIconFever }
            // ctx.drawImage(thisIcon, dotX - 10, dotY - 10, 20, 20)
            ctx.beginPath();

            ctx.arc(dot.x, dot.y, 7, 0, Math.PI * 2);
            ctx.strokeStyle = '#264'
            ctx.lineWidth = 2
            ctx.stroke()

            ctx.arc(dot.x, dot.y, 6, 0, Math.PI * 2);
            ctx.fillStyle = '#2f5'
            ctx.fill();
            if (zoomNow >= 12) {
                ctx.font = 'bold 14px serif';
                ctx.fillStyle = '#2e5'
                ctx.fillText(name, dot.x + 10, dot.y + 5)
            }
            ctx.closePath();
        }
    }
    for (i = 0; i < limited2.length; i++) {
        lat = parseFloat(limited2[i]['lat'])
        lng = parseFloat(limited2[i]['lng'])
        name = limited2[i]['name_fmt']

        if (info.bounds.contains([lat, lng])) {
            dot = canvasOverlay._map.latLngToContainerPoint([lat, lng]);
            dotX = dot.x; dotY = dot.y
            // if (ct == clickedSeq) { thisIcon = hospitalIconRescue; console.log(addr) } else { thisIcon = hospitalIconFever }
            // ctx.drawImage(thisIcon, dotX - 10, dotY - 10, 20, 20)
            ctx.beginPath();

            ctx.arc(dot.x, dot.y, 7, 0, Math.PI * 2);
            ctx.strokeStyle = '#e10'
            ctx.lineWidth = 2
            ctx.stroke()

            ctx.arc(dot.x, dot.y, 6, 0, Math.PI * 2);
            ctx.fillStyle = '#e81'
            ctx.fill();

            if (zoomNow >= 12) {
                ctx.font = 'bold 14px serif';
                ctx.fillStyle = '#fc3'
                ctx.fillText(name, dot.x + 10, dot.y + 5)
            }

            ctx.closePath();
        }
    }
    // for (i = 0; i < excluded2.length; i++) {
    //     lat = parseFloat(excluded2[i]['lat'])
    //     lng = parseFloat(excluded2[i]['lng'])
    //     name = excluded2[i]['name_fmt']

    //     if (info.bounds.contains([lat, lng])) {
    //         dot = canvasOverlay._map.latLngToContainerPoint([lat, lng]);
    //         dotX = dot.x; dotY = dot.y
    //         // if (ct == clickedSeq) { thisIcon = hospitalIconRescue; console.log(addr) } else { thisIcon = hospitalIconFever }
    //         // ctx.drawImage(thisIcon, dotX - 10, dotY - 10, 20, 20)
    //         ctx.beginPath();

    //         ctx.arc(dot.x, dot.y, 7, 0, Math.PI * 2);
    //         ctx.strokeStyle = '#333'
    //         ctx.lineWidth = 2
    //         ctx.stroke()

    //         ctx.arc(dot.x, dot.y, 6, 0, Math.PI * 2);
    //         ctx.fillStyle = '#777'
    //         ctx.fill();

    //         if (showLabels) {
    //             ctx.font = 'bold 14px serif';
    //             ctx.fillStyle = '#bbb'
    //             ctx.fillText(name, dot.x + 10, dot.y + 5)
    //         }

    //         ctx.closePath();
    //     }
    // }
}

function addHospitals2(availType, svc, hospitals, color, cirColor, fontColor, hospitalGrp) {
    var iconOptions = {
        color: "rgb(0,0,100)",
        className: 'src-lookup-prompt',
        iconSize: [22, 22],
        circleRatio: 0.86,
        circleWeight: 2.5,
        circleOpacity: 0,
        circleFillOpacity: 1,
        circleColor: '#000',
        circleFillColor: color,
        popupAnchor: [0, -2],
    }

    for (i = 0; i < hospitals.length; i++) {
        lat = parseFloat(hospitals[i]['lat'])
        lng = parseFloat(hospitals[i]['lng'])

        if (isNaN(lat)) continue
        // if (showLabels) iconOptions['cirTxt'] = hospitals[i]['name_fmt']

        iconOptions['coords'] = [lng, lat]
        var thisMarker = new L.Marker.SVGMarker(L.latLng([lat, lng]), {
            iconOptions: iconOptions
        })

        if (hospitals[i]['alias'] == '') {
            var alias = '-'
        } else {
            var alias = hospitals[i]['alias']
        }

        if (hospitals[i]['tel_gaode'] == '') {
            var tel = '-'
        } else {
            var tel = hospitals[i]['tel_gaode']
        }


        if (hospitals[i]['spec'] == 'nan') {
            var spec = '-'
        } else {
            var spec = hospitals[i]['spec']
        }

        if (svc == 'tumor') {
            spec += '；' + hospitals[i]['condition']
        }

        popupContent = ''
        if (['kidney', 'heart', 'brain', 'surgery'].includes(svc)) {
            if (hospitals[i]['condition'] == undefined) {
                validity = '已核实'
            } else {
                validity = hospitals[i]['condition']
            }
            popupContent += '<div><b>核实情况：</b>' + validity + '</div>'
        }
        if (spec == '') specText = '-'
        else specText = spec

        tel1 = ''; tel2 = ''
        for (k = 0; k < (hospitals[i]['tel'].split(';')).length; k ++) {
            tel1 += '<a href="tel:' + hospitals[i]['tel'].split(';')[k] + '">' + hospitals[i]['tel'].split(';')[k] + '</a>' + '；'
        }
        for (k = 0; k < (tel.split(';')).length; k ++) {
            tel2 += '<a href="tel:' + (tel.split(';'))[k] + '">' + (tel.split(';'))[k] + '</a>' + '；'
        }

        popupContent +=
            '<div>医院名称：' + hospitals[i]['name_fmt'] + '</div>' +
            '<div>医院别名：' + alias + '</div>' +
            '<div>医院类型：' + hospitals[i]['type2'] + '</div>' +
            '<div>地址：' + hospitals[i]['addr'] + '</div>' +
            '<div>医院电话：' + tel1.slice(0,-1) + '</div>' +
            '<div>医院电话（来自高德地图）：' + tel2.slice(0,-1) + '</div>' +
            '<div>详情：' + specText + '</div>'

        // console.log(popupContent)
        var popup = L.popup({ 'closeButton': false })
            .setLatLng(L.latLng([lat, lng]))
        //     .setContent(popupContent)
        if (availType == 'inc2') {
            specsInc2.push(popupContent)
            coordsInc2.push([lng, lat])
            markersInc2.push(thisMarker)
        }
        if (availType == 'ltd2') {
            specsLtd2.push(popupContent)
            coordsLtd2.push([lng, lat])
            markersLtd2.push(thisMarker)
        }

        // thisMarker.bindPopup(popup).openPopup()
        hospitalGrp.push(thisMarker)
    }
}
var highlightedHospital
function addHospitals(availType, hospitals, color, cirColor, fontColor, hospitalGrp) {
    var iconOptions = {
        color: "rgb(0,0,100)",
        className: 'src-lookup-prompt',
        iconSize: [22, 22],
        circleRatio: 0.86,
        circleWeight: 2.5,
        circleOpacity: 0,
        circleFillOpacity: 1,
        circleColor: '#000',
        circleFillColor: color,
        popupAnchor: [0, -2]
    }
    for (i = 0; i < hospitals.length; i++) {
        lat = hospitals[i]['lat8']
        lng = hospitals[i]['lng8']
        iconOptions['coords'] = [lng, lat]

        var thisMarker = new L.Marker.SVGMarker(L.latLng([lat, lng]), {
            iconOptions: iconOptions
        })

        if (hospitals[i]['normalPregnant'] == 1) { var npc = '#2d5' }
        if (hospitals[i]['normalPregnant'] == 0) { var npc = '#d71' }
        if (hospitals[i]['normalPregnant'] == -1) { var npc = '#777' }

        if (hospitals[i]['suspectConfirmedPregnant'] == 1) { var spc = '#2d5' }
        if (hospitals[i]['suspectConfirmedPregnant'] == 0) { var spc = '#d71' }
        if (hospitals[i]['suspectConfirmedPregnant'] == -1) { var spc = '#777' }

        if (hospitals[i]['normalPregnancyCheck'] == 1) { var ncc = '#2d5' }
        if (hospitals[i]['normalPregnancyCheck'] == 0) { var ncc = '#d71' }
        if (hospitals[i]['normalPregnancyCheck'] == -1) { var ncc = '#777' }

        if (hospitals[i]['ultraB'] == 1) { var bcc = '#2d5' }
        if (hospitals[i]['ultraB'] == 0) { var bcc = '#d71' }
        if (hospitals[i]['ultraB'] == -1) { var bcc = '#777' }

        if (hospitals[i]['deformityExclusion'] == 1) { var dexc = '#2d5' }
        if (hospitals[i]['deformityExclusion'] == 0) { var dexc = '#d71' }
        if (hospitals[i]['deformityExclusion'] == -1) { var dexc = '#777' }

        if (hospitals[i]['delivery'] == 1) { var dc = '#2d5' }
        if (hospitals[i]['delivery'] == 0) { var dc = '#d71' }
        if (hospitals[i]['delivery'] == -1) { var dc = '#777' }

        if (hospitals[i]['naCheck'] == 1) { var nacc = '#2d5' }
        if (hospitals[i]['naCheck'] == 0) { var nacc = '#d71' }
        if (hospitals[i]['naCheck'] == -1) { var nacc = '#777' }

        if (hospitals[i]['hospitalAlias'] == '') {
            var alias = '-'
        } else {
            var alias = hospitals[i]['hospitalAlias']
        }

        if (hospitals[i]['tel_GaodeMapAPI'] == '') {
            var tel = '-'
        } else {
            var tel = hospitals[i]['tel_GaodeMapAPI']
        }

        tel2 = ''
        // for (k = 0; k < (hospitals[i]['tel'].split(';')).length; k ++) {
        //     tel1 += '<a href="tel:' + hospitals[i]['tel'].split(';')[k] + '">' + hospitals[i]['tel'].split(';')[k] + '</a>' + '；'
        // }
        for (k = 0; k < (tel.split(';')).length; k ++) {
            tel2 += '<a href="tel:' + (tel.split(';'))[k] + '">' + (tel.split(';'))[k] + '</a>' + '；'
        }
        popupContent =
            '<div>消息有效性：' + hospitals[i]['validity'] + '</div>' +
            '<div>医院名称：' + hospitals[i]['hospitalName'] + '</div>' +
            '<div>医院别名：' + alias + '</div>' +
            '<div>地址：' + hospitals[i]['address'] + '</div>' +
            '<div>医院电话（来自高德地图）：' + tel2.slice(0,-1) + '</div>' +

            '<br><div>普通孕妇：<div style="display: inline; color:' + npc + '">' + hospitals[i]['normalPregnant2'] + '</div></div>' +
            '<div>新冠肺炎疑似/确诊孕妇：<div style="display: inline; color:' + spc + '">' + hospitals[i]['suspectConfirmedPregnant2'] + '</div></div>' +
            '<div>常规产检：<div style="display: inline;color:' + ncc + '">' + hospitals[i]['normalPregnancyCheck2'] + '</div></div>' +
            '<div>孕期产检B超：<div style="display: inline;color:' + bcc + '">' + hospitals[i]['ultraB2'] + '</div></div>' +

            '<br><div>中孕期三维排畸彩超（大排畸）：<div style="display: inline;color:' + dexc + '">' + hospitals[i]['deformityExclusion2'] + '</div></div>' +
            '<div>接生：<div style="display: inline;color:' + dc + '">' + hospitals[i]['delivery2'] + '</div></div>' +

            '<br><div>核酸检测：<div style="display: inline;color:' + nacc + '">' + hospitals[i]['naCheck2'] + '</div></div>'
        try {
            popupContent += '<br><div>详情：<div style="display: inline">' + hospitals[i]['info'].replace(/-/g, '') + '</div></div>'
        } catch {}

        var popup = L.popup({ 'closeButton': false })
            .setLatLng(L.latLng([lat, lng]))
        //     .setContent(popupContent)
        if (availType == 'ltd1') {
            specsLtd1.push(popupContent)
            coordsLtd1.push(popupContent)
            markersLtd1.push(thisMarker)
        }
        if (availType == 'inc1') {
            specsInc1.push(popupContent)
            coordsInc1.push(popupContent)
            markersInc1.push(thisMarker)
        }
        // thisMarker.bindPopup(popup).openPopup()
        hospitalGrp.push(thisMarker)
    }
}
var gh; var hh; var wuhan_dialysis; var wuhan_tumor; var wuhan_emergency
function highlight_deptBtn() {
    $('.dept-btn').each(function () {
        $(this).css('background', '#fff')
        $(this).children('span').css('color', '#000')
    })
    $(this).css('background', '#8636FF')
    $(this).children('span').css('color', '#fff')
}

function prep_hospitals(data) {
    console.log(data.length)
    $('#ranking-cont').on('scroll', function () {
        console.log('scrolled', $('#r6').css('padding-top'))
    })

    // var zoomed = d3.scale()
    //     .on('scale', function(e) {
    //        tr = d3.event.transform
    //        console.log(tr.k, tr.x, tr.y)
    //     })
    // d3.select('#ranking-cont').call(zoomed)


    updateHospitalLayer2()
    updateHospitalLayer1()
    let gh = data[0]['gh']
    let hh = data[1]['all']
    let wuhan_dialysis = data[2]['all']
    let wuhan_tumor = data[3]['all']
    let wuhan_emergency = data[4]['all']

    $('.service').hide()

    $('#gyn-s').height($('#gyn-s-2').height())
    $('.hospitalType').height(72 + $('#gyn-s').height())
    // maxHStr = 'calc(100% - ' 
    //     + (74 + $('#gyn-s').height() + $('#hList').height()) + 'px)'
    $('#introText').css('top', 74 + $('#gyn-s').height())//.css('max-height', maxHStr).css('min-height', '30%')

    $('.dept-btn').off(highlight_deptBtn).click(highlight_deptBtn)
    $('.dept-btn').click(function () {
        svcSelected = []
        included = []
        limited = []
        excluded = []
        var promptHeight = 0
        if (this.id == 'gyn') {
            $('#svc-prompt').html('<b>寻找武汉孕妇医疗服务请选择具体服务：</b>')

            loadFuncId = 1
            $('#gyn-s').show()
            $('#nac-s').hide()
            $('#ped-s').hide()
            $('#emg-s').hide()
            $('#tumor-s').hide()
            $('#kidney-s').hide()

            $('[name="gynType"]').prop('checked', false)

            filterSvc('preg', hh, [])

            $('[name="gynType"]').off('click').click(function () {

                svcSelected = []
                included = []
                limited = []
                excluded = []
                $('[name="gynType"]').each(function () {
                    if (this.checked) {
                        svcSelected.push(this.value)
                    }
                })
                filterGyn(svcSelected, gh, [])
            })
            promptHeight = $('#gyn-s-2').height() + 15

        }
        if (this.id == 'nac') {
            $('#svc-prompt').html('')

            loadFuncId = 2
            $('#gyn-s').hide()
            $('#ped-s').hide()
            $('#nac-s').show()
            $('#emg-s').hide()
            $('#tumor-s').hide()
            $('#kidney-s').hide()

            filterSvc('nac', hh, [])
            promptHeight = $('#nac-s').height()
        }
        if (this.id == 'emg') {
            loadFuncId = 2
            $('#gyn-s').hide()
            $('#ped-s').hide()
            $('#nac-s').hide()
            $('#emg-s').show()
            $('#tumor-s').hide()
            $('#kidney-s').hide()
            filterSvc('emergency', hh, [])

            $('[name="emgType"]').off('click').click(function () {
                svcSelected = []
                included = []
                limited = []
                excluded = []
                filterSvc(this.value, hh, wuhan_emergency)
            })

            $('#svc-prompt').html('<b>寻找武汉急诊服务请选择具体服务类型：</b>')
            promptHeight = $('#emg-s').height() + 15
        }
        if (this.id == 'tumor') {
            loadFuncId = 2
            $('#gyn-s').hide()
            $('#ped-s').hide()
            $('#nac-s').hide()
            $('#emg-s').hide()
            $('#tumor-s').show()
            $('#kidney-s').hide()
            filterSvc('tumor', hh, wuhan_tumor)

            $('#svc-prompt').html('')
            promptHeight = $('#tumor-s').height()
        }
        if (this.id == 'kidney') {
            loadFuncId = 2
            $('#gyn-s').hide()
            $('#ped-s').hide()
            $('#nac-s').hide()
            $('#emg-s').hide()
            $('#tumor-s').hide()
            $('#kidney-s').show()
            filterSvc('kidney', hh, wuhan_dialysis)

            $('#svc-prompt').html('')
            promptHeight = $('#kidney-s').height()
        }
        if (this.id == 'ped') {
            loadFuncId = 2
            $('#gyn-s').hide()
            $('#ped-s').show()
            $('#nac-s').hide()
            $('#emg-s').hide()
            $('#tumor-s').hide()
            $('#kidney-s').hide()
            filterSvc('ped', hh, [])

            $('#svc-prompt').html('<b>提示：武汉无儿科数据</b>')
            promptHeight = $('#ped-s').height() + 15
        }

        $('#gyn-s').height(promptHeight + 3)
        $('.hospitalType').height(72 + promptHeight)
    })
}
var included2 = []; var excluded2 = []; var limited2 = []

var specsLtd2 = []; var specsInc2 = []
var specsLtd1 = []; var specsInc1 = [];

var coordsLtd2 = []; var coordsInc2 = []
var coordsLtd1 = []; var coordsInc1 = []

var markersLtd1 = []; var markersInc1 = []
var markersLtd2 = []; var markersInc2 = []
function filterSvc(svc, hh, wuhan) {
    included2 = []
    excluded2 = []
    limited2 = []

    specsLtd2 = []
    specsInc2 = []
    for (i = 0; i < wuhan.length; i++) {
        if (wuhan[i]['addr'] == '404') continue
        if (svc == 'brain') {
            if (wuhan[i]['avail'] == true && wuhan[i]['brainInfar'] == 1) {
                included2.push(wuhan[i])
            } else if (wuhan[i]['avail'] == true && wuhan[i]['brainInfar'] == 0) {
                limited2.push(wuhan[i])
            } else {
                excluded2.push(wuhan[i])
            }
        } else if (svc == 'heart') {
            if (wuhan[i]['avail'] == true && wuhan[i]['heartInfar'] == 1) {
                included2.push(wuhan[i])
            } else if (wuhan[i]['avail'] == true && wuhan[i]['heartInfar'] == 0) {
                limited2.push(wuhan[i])
            } else {
                excluded2.push(wuhan[i])
            }
        } else if (svc == 'surgery') {
            if (wuhan[i]['avail'] == true && wuhan[i]['surgery'] == 1) {
                included2.push(wuhan[i])
            } else if (wuhan[i]['avail'] == true && wuhan[i]['surgery'] == 0) {
                limited2.push(wuhan[i])
            } else {
                excluded2.push(wuhan[i])
            }
        } else {
            if (wuhan[i]['avail'] == true) {
                included2.push(wuhan[i])
            } else {
                excluded2.push(wuhan[i])
            }
        }
    }

    for (i = 0; i < hh.length; i++) {
        if (hh[i]['addr'] == '404') continue
        if (['emergency', 'heart', 'brain', 'surgery'].includes(svc)) {
            if (hh[i]['categ'][0] == true) {
                included2.push(hh[i])
            }
        }
        if (svc == 'kidney') {
            // console.log(hh[i]['categ'][1])
            if (hh[i]['categ'][1] == true) {
                included2.push(hh[i])
            }
        }
        if (svc == 'tumor') {
            if (hh[i]['categ'][2] == true) {
                included2.push(hh[i])
            }
        }
        if (svc == 'ped') {
            if (hh[i]['categ'][3] == true) {
                included2.push(hh[i])
            }
        }
        if (svc == 'preg') {
            if (hh[i]['categ'][4] == true) {
                included2.push(hh[i])
            }
        }
    }
    for (i = 0; i < wuhan.length; i++) {
        if (['emergency', 'tumor', 'dialysis'].includes(svc)) {
            if (wuhan[i]['avail'] == true) {
                included2.push(wuhan[i])
            } else {
                excluded2.push(wuhan[i])
            }
        }
    }
    loadPoints2(svc)
}
var hospitalCont2
var hospitalGrp2 = []
var specs2 = []
function donothign() { }
function loadPoints2(svc) {
    if (map.hasLayer(hospitalCont)) { hospitalCont.removeFrom(map) }
    if (map.hasLayer(hospitalCont2)) { hospitalCont2.removeFrom(map) }

    hospitalLayer1.redraw()
    hospitalLayer2.redraw()

    hospitalGrp2 = []
    specs2 = []
    markersInc2 = []; markersLtd2 = []

    addHospitals2('inc2', svc, included2, '#2f5', '#ff0', '#2f5', hospitalGrp2)
    addHospitals2('ltd2', svc, limited2, '#e81', '#e10', '#fa1', hospitalGrp2)
    // addHospitals2('', svc, excluded2, '#777', '#333', '#bbb', hospitalGrp2)

    $('.src-lookup-prompt-circle')
        .off('mouseover')
        .on('mouseover', function () {
            $(this).attr('opacity', 1)
        })
        .off('mouseout')
        .on('mouseout', function () {
            $(this).attr('opacity', 0)
        })
    hospitalCont2 = L.layerGroup(hospitalGrp2)
    hospitalCont2.addTo(map)

    geoPosList()

}

function filterGyn(svcSelected, gh) {
    specsInc1 = []; specsLtd1 = []
    for (i = 0; i < gh.length; i++) {
        var includeThis = false
        var limitThis = false
        var excludeThis = false
        // console.log(svcSelected.includes('np'), gh[i]['normalPregnant'])
        if (svcSelected.includes('np')) {
            if (gh[i]['normalPregnant'] == 1) {
                includeThis = true
            }
            if (gh[i]['normalPregnant'] == 0) {
                limitThis = true
            }
            if (gh[i]['normalPregnant'] == -1) {
                excludeThis = true
            }
        }
        if (svcSelected.includes('sp')) {
            if (gh[i]['suspectConfirmedPregnant'] == 1) {
                includeThis = true
            }

            if (gh[i]['suspectConfirmedPregnant'] == 0) {
                limitThis = true
            }

            if (gh[i]['suspectConfirmedPregnant'] == -1) {
                excludeThis = true
            }
        }
        if (svcSelected.includes('nc')) {
            if (gh[i]['normalPregnancyCheck'] == 1) {
                includeThis = true
            }

            if (gh[i]['normalPregnancyCheck'] == 0) {
                limitThis = true
            }

            if (gh[i]['normalPregnancyCheck'] == -1) {
                excludeThis = true
            }
        }
        if (svcSelected.includes('Bc')) {
            if (gh[i]['ultraB'] == 1) {
                includeThis = true
            }

            if (gh[i]['ultraB'] == 0) {
                limitThis = true
            }

            if (gh[i]['ultraB'] == -1) {
                excludeThis = true
            }
        }
        if (svcSelected.includes('dex')) {
            if (gh[i]['deformityExclusion'] == 1) {
                includeThis = true
            }

            if (gh[i]['deformityExclusion'] == 0) {
                limitThis = true
            }

            if (gh[i]['deformityExclusion'] == -1) {
                excludeThis = true
            }
        }
        if (svcSelected.includes('d')) {
            if (gh[i]['delivery'] == 1) {
                includeThis = true
            }
            if (gh[i]['delivery'] == 0) {
                limitThis = true
            }
            if (gh[i]['delivery'] == -1) {
                excludeThis = true
            }
        }

        if (excludeThis == true) {
            excluded.push(gh[i])
        } else {
            if (limitThis == true) {
                limited.push(gh[i])
            } else {
                if (includeThis == true) {
                    included.push(gh[i])
                }
            }
        }
    }
    // console.log(included)
    loadPoints()
}
var curPos = []
function gotPos(position) {
    posPrompt = '距您'

    var lat = position.coords.latitude;
    var lng = position.coords.longitude;
    map.flyTo(L.latLng(lat, lng), 11, { 'animate': true, 'duration': 0.6, 'easeLinearity': 0.1 })

    // var lat = 30.55
    // var lng = 114.28
    $('#loc').html('lat' + String(lat) + 'lng' + String(lng))
    var iconOptions = {
        color: "rgb(0,0,100)",
        className: 'posMarker',
        iconSize: [18, 18],
        circleRatio: 0.9,
        circleWeight: 2,
        circleOpacity: 1,
        circleFillOpacity: 1,
        circleColor: '#fff',
        circleFillColor: '#0f81f2',
    }
    var posMarker = new L.Marker.SVGMarker(L.latLng([lat, lng]), {
        iconOptions: iconOptions
    }).addTo(map)
    curPos = [lng, lat]
}

var userDefLat; var userDefLng

// function getUserDefLatlng() {
//     curLat = map.containerPointToLatLng(L.point($('#map').width() / 2 - 11, $('#map').height() / 2.5 - 11))['lat']
//     curLng = map.containerPointToLatLng(L.point($('#map').width() / 2 - 11, $('#map').height() / 2.5 - 11))['lng']
//     console.log(curLat, curLng)
//     prep_hospitals_2()
// }

var posPrompt = '距武汉'
function errPos(err) {
    console.log('err on pos', err.code)
    alert('无法定位，默认定位为武汉市')
    posPrompt = '距武汉'
    var iconOptions = {
        color: "rgb(0,0,100)",
        className: 'posMarker',
        iconSize: [18, 18],
        circleRatio: 0.9,
        circleWeight: 2,
        circleOpacity: 1,
        circleFillOpacity: 1,
        circleColor: '#fff',
        circleFillColor: '#0f81f2',
    }
    curLat = 30.55
    curLng = 114.28
    var posMarker = new L.Marker.SVGMarker(L.latLng([curLat, curLng]), {
        iconOptions: iconOptions
    }).addTo(map)
    // console.log(d3.select('body'), $('body').width() / 2)

    // $('#userDefLoc').css('left', $('#map').width() / 2 - 11)
    //     .css('top', $('#map').height() / 2.5 - 11)
    // map.on('moveend', getUserDefLatlng())
    // userDefLoc = d3.select('#userDefLoc')
    //     .append('svg')
    //     .style('position', 'absolute')
    //     .style('height', 22)
    //     .style('width', 22)
    // userDefLoc.append('circle')
    //     .attr('class', "posMarker-circle")
    //     .attr('cx', "9")
    //     .attr('cy', "9")
    //     .attr('r', "8.1")
    //     .attr('opacity', "1")
    //     .attr('fill', "#0f81f2")
    //     .attr('fill-opacity', "1")
    //     .attr('stroke', "#fff")
    //     .attr('stroke-opacity', "1")
    //     .attr('stroke-width', "2")
}

function geoPosList() {

    console.log(curLng, curLat)
    if (curLng == -999) {
        curLng = curPos[0]; curLat = curPos[1]
    }
    // if (curPos != []) {
    //     curLng = curPos[0]; curLat = curPos[1]
    // } else {
    // }

    // console.log('called NEW GEO POS List', curLng, curLat)
    // userDefLoc = d3.select('#map')
    //     .append('svg')
    //     .style('position', 'absolute')
    //     .style('top', $('#map').height() / 2)
    //     .style('left', $('#map').width() / 2)
    // userDefLoc.append('circle')
    //     .attr('class', "posMarker-circle")
    //     .attr('cx', "9")
    //     .attr('cy', "9")
    //     .attr('r', "8.1")
    //     .attr('opacity', "1")
    //     .attr('fill', "#0f81f2")
    //     .attr('fill-opacity', "1")
    //     .attr('stroke', "#fff")
    //     .attr('stroke-opacity', "1")
    //     .attr('stroke-width', "2")
    console.log(curLng, curLat, curPos)
    inc = included.concat(included2)
    ltd = limited.concat(limited2)
    specsInc = specsInc1.concat(specsInc2)
    specsLtd = specsLtd1.concat(specsLtd2)
    markersInc = markersInc1.concat(markersInc2)

    while (true) {
        if (curPos == []) { setTimeout(200) }
        else { break }
    }


    var inc2List = []
    var inc2Lnglat = ''
    var inc2Coords = []
    var inc2Specs = []
    var inc2Markers = []

    var ltd2List = []
    var ltd2Lnglat = ''
    var ltd2Coords = []
    var ltd2Specs = []
    var ltd2Markers = []
    console.log('permmmmmmmm', inc, ltd)
    for (i = 0; i < inc.length; i++) {
        if ('lng8' in inc[i]) { lngName = 'lng8' }
        else { lngName = 'lng' }

        if ('lat8' in inc[i]) { latName = 'lat8' }
        else { latName = 'lat' }

        dist = calcDist(lng, lat, inc[i][lngName], inc[i][latName])

        inc[i]['availability'] = 1
        inc2Specs.push(specsInc[i])
        inc2List.push(inc[i])
        inc2Lnglat += String(inc[i][latName]) + ',' + String(inc[i][lngName]) + ';'
        inc2Coords.push([inc[i][lngName], inc[i][latName]])
        inc2Markers.push(markersInc[i])
    }

    for (i = 0; i < ltd.length; i++) {
        if ('lng8' in ltd[i]) { lngName = 'lng8' }
        else { lngName = 'lng' }

        if ('lat8' in ltd[i]) { latName = 'lat8' }
        else { latName = 'lat' }

        dist = calcDist(lng, lat, ltd[i][lngName], ltd[i][latName])

        ltd[i]['availability'] = 0
        ltd2Specs.push(specsLtd[i])
        ltd2List.push(ltd[i])
        ltd2Lnglat += String(ltd[i][latName]) + ',' + String(ltd[i][lngName]) + ';'
        ltd2Coords.push([ltd[i][lngName], ltd[i][latName]])
        ltd2Markers.push(markersInc[i])
    }
    getMatrix(inc2Specs, ltd2Specs, inc2List, ltd2List, inc2Lnglat + ltd2Lnglat, inc2Coords, ltd2Coords, inc2Markers, ltd2Markers, inc2List.length)

}

var curLat = -999; var curLng = -999
function getMatrix(inc2Specs, ltd2Specs, inc2List, ltd2List, strLnglat, inc2Coords, ltd2Coords, inc2Markers, ltd2Markers, lenInc) {
    var combined = inc2List.concat(ltd2List)
    var combinedCoords = inc2Coords.concat(ltd2Coords)
    var combinedSpecs = inc2Specs.concat(ltd2Specs)
    var combinedMarkers = inc2Markers.concat(ltd2Markers)
    console.log('length after combinationnnnnnnnnnnnn', strLnglat)
    if (curLat == undefined) curLat = 30.55
    if (curLng == undefined) curLng = 114.28
    url = 'https://apis.map.qq.com/ws/distance/v1/matrix/?mode=bicycling' +
        '&from=' + String(curLat) + ',' + String(curLng) +
        '&to=' + strLnglat.slice(0, -1) +
        '&output=jsonp' +
        '&key=OLYBZ-ZNCK2-QWPUM-CMSRY-FPCCV-VRF5N'

    console.log('fetching data from ', url)
    $.ajax({
        url: url,
        type: "get",
        async: false,
        dataType: "jsonp",
        crossDomain: true,
        success: function (res) {
            var tmapR = []
            for (i = 0; i < res.result['rows'][0]['elements'].length; i++) {
                tmapR.push(res.result['rows'][0]['elements'][i]['distance'])
            }
            updateList(tmapR, combined, combinedSpecs, combinedCoords, combinedMarkers)
        },
        error: function (err) {
            console.log('err', err)
        }
    })
}

var lastExpanded = -2
function updateList(tmapR, combined, combinedSpecs, combinedCoords, combinedMarkers) {
    console.log('gen listOOOOOOOOOOOO', combinedMarkers)
    var newDists = []
    var newCombined = []
    var newSpecs = []
    var newCoords = []
    var newMarkers = []

    // rank distance from nearest to farest
    while (tmapR.length > 0) {
        curMax = 0
        curMaxIdx = -1
        for (k = 0; k < tmapR.length; k++) {
            if (tmapR[k] > curMax) {
                curMax = tmapR[k]
                curMaxIdx = k
            }
        }
        newDists.push(curMax)
        newCombined.push(combined[curMaxIdx])
        newSpecs.push(combinedSpecs[curMaxIdx])
        newCoords.push(combinedCoords[curMaxIdx])
        newMarkers.push(combinedMarkers[curMaxIdx])

        tmapR.splice(curMaxIdx, 1)
        combined.splice(curMaxIdx, 1)
        combinedSpecs.splice(curMaxIdx, 1)
        combinedCoords.splice(curMaxIdx, 1)
        combinedMarkers.splice(curMaxIdx, 1)
    }

    newDists.reverse()
    newCombined.reverse()
    newSpecs.reverse()
    newCoords.reverse()
    newMarkers.reverse()

    $('#ranking-cont').empty()
    var listItem
    var count50km = 0
    var detHeights = []
    var keyHeights = []
    var expanded = []
    for (k = 0; k < newDists.length; k++) {
        if ((newDists[k] / 1000) <= 50) {
            count50km += 1
        }

        if ('name_fmt' in newCombined[k]) { hospitalName = 'name_fmt' }
        else { hospitalName = 'hospitalName' }

        if ('addr' in newCombined[k]) { addressContent = 'addr' }
        else { addressContent = 'address' }

        if ('city' in newCombined[k]) { cityName = newCombined[k]['city'] }
        else { cityName = '武汉市' }

        listItemName = '<div class="key-info line1"><div class="key-info hospital-name">' + newCombined[k][hospitalName] + '</div>'

        if (newCombined[k]['availability'] == 1) {
            listItemAvail = '<br><div class="key-info line2"><div class="key-info services all-services">提供所有选中服务</div>'
        } else {
            listItemAvail = '<br><div class="key-info line2"><div class="key-info services some-services">提供部分所选服务</div>'
        }

        listItemDist = '<div class="key-info dist">' + posPrompt + (newDists[k] / 1000).toFixed(1) + 'km</div></div>'

        listItemAddr = '<div class="key-info addr">' + cityName.replace('恩施土家族苗族自治州', '恩施州') + '-' + newCombined[k][addressContent] + '</div></div>'

        listSpec = '<div class="det-info"><div><b>医院详细信息：</b></div>' + newSpecs[k] + '</div>'

        listItem = '<div class="ranking-el" id="r' + String(k) + '">' + listItemName + listItemDist + listItemAvail + listItemAddr + listSpec + '</div>'

        $('#ranking-cont').append(listItem)

        latest = document.getElementById('ranking-cont').lastChild

        height3 = $(latest).find('.det-info').hide()
        expanded.push(0)

        height1 = $(latest).find('.key-info.line1').height()
        height2 = $(latest).find('.key-info.line2').height()
        height3 = $(latest).find('.det-info').height()
        detHeights.push(height3)
        keyHeights.push(height1 + height2 + 4)

        $(latest).css('height', height1 + height2 + 4)
        $(latest).find('.det-info').css('margin-top', height2 + 5).css('margin-left', '5px')
        $(latest).css('padding-top', '2px')
        $(latest).css('padding-bottom', '8px')
    }
    $('#show-count').html('<div>找到湖北省内共<div class="show-count-num"><b>' + newDists.length + '</b></div>家，</div><div>' + posPrompt + '50km内共<div class="show-count-num"><b>' + count50km + '</b></div>家符合条件的医院')
    var highlightedOption_ltd = {
        color: "rgb(0,0,100)",
        className: 'highlightedHospital',
        iconSize: [22, 22],
        circleRatio: 0.86,
        circleWeight: 2.5,
        circleOpacity: 1,
        circleFillOpacity: 1,
        circleColor: '#000',
        circleFillColor: '#fa1',
    }
    var highlightedOption_inc = {
        color: "rgb(0,0,100)",
        className: 'highlightedHospital',
        iconSize: [22, 22],
        circleRatio: 0.86,
        circleWeight: 2.5,
        circleOpacity: 1,
        circleFillOpacity: 1,
        circleColor: '#000',
        circleFillColor: '#2f5',
    }

    $('.src-lookup-prompt-circle')
        .off('mouseover')
        .on('mouseover', function () {
            console.log('mouseovered 11')
            $(this).attr('opacity', 1)
        })
        .off('click')
        .on('click', function () {
            console.log('clicked 11')
            $('.src-lookup-prompt-circle').each(function (i) {
                $(this).attr('opacity', 0)
            })
            $(this).attr('opacity', 1)

            coordsIdentifier = $(this).attr('coords')
            for (k = 0; k < newCoords.length; k++) {
                if (String(newCoords[k][0]) + ',' + String(newCoords[k][1]) == coordsIdentifier) {
                    if (lastExpanded != -2) {
                        $('#ranking-cont > div:nth-child(' + String(lastExpanded + 1) + ')').animate({ 'height': keyHeights[lastExpanded] }, 250)
                        $('#ranking-cont > div:nth-child(' + String(lastExpanded + 1) + ')').find('.det-info').hide()
                    }
                    $('#ranking-cont > div:nth-child(' + String(k + 1) + ')').find('.det-info').show()
                    lastExpanded = k
                    expandedHeight = detHeights[k] + keyHeights[k]
                    console.log('CFM', $('#ranking-cont > div:nth-child(' + String(k + 1) + ')'), $('#ranking-cont > div:nth-child(' + String(k + 1) + ')').find('.det-info'))
                    console.log('CFM2', expandedHeight, document.getElementById('r' + String(k)))
                    $('#r' + String(k)).animate({ 'height': expandedHeight }, 260, function () {
                        this.scrollIntoView({ behavior: "smooth" })
                    })
                }
            }
        })
        .off('mouseout')
        .on('mouseout', function () {
            console.log('de-highlight')
            $(this).attr('opacity', 0)
        })

    $('.ranking-el').off('click').on('click', function () {
        if (map.hasLayer(highlightedHospital)) { highlightedHospital.removeFrom(map) }
        clicked = this

        zoomNow = map.getZoom()
        if (zoomNow == '12') {
            timeoutLength = 0
        } else {
            map.setZoom(12)
            timeoutLength = 320
        }
        setTimeout(function () {
            console.log(lastExpanded, $('#ranking-cont > div:nth-child(' + String(lastExpanded + 1) + ')'))
            if (lastExpanded != -1) {
                expanded[lastExpanded] = 0

                $('#ranking-cont > div:nth-child(' + String(lastExpanded + 1) + ')').animate({ 'height': keyHeights[lastExpanded] }, 250)
                $('#ranking-cont > div:nth-child(' + String(lastExpanded + 1) + ')').find('.det-info').hide()

            }

            seq = parseInt($(clicked).attr('id').replace('r', ''))
            expandedHeight = detHeights[seq] + keyHeights[seq]
            if (expanded[seq] == 0 && lastExpanded != seq) {
                expanded[seq] = 1
                lastExpanded = seq
                $(clicked).find('.det-info').show()
                lastExpanded = parseInt(String(seq))
                map.panTo([newCoords[seq][1], newCoords[seq][0]], { 'animate': true, 'duration': 0.6, 'easeLinearity': 0.1 })

                if (newCombined[seq]['availability'] == 1) {
                    thisIconOpt = highlightedOption_inc
                } else if (newCombined[seq]['availability'] == 0) {
                    thisIconOpt = highlightedOption_ltd
                }

                $('.src-lookup-prompt-circle').each(function (i) {
                    if ($(this).attr('coords') == String(newCoords[seq][0]) + ',' + newCoords[seq][1].toString()) {
                        $(this).attr('opacity', 1)
                    } else {
                        $(this).attr('opacity', 0)
                    }
                })

                $(clicked).animate({ 'height': expandedHeight }, 320, function () {
                    document.getElementById('r' + String(seq)).scrollIntoView({ behavior: "smooth" })
                })
            }
            else if (lastExpanded == seq) {
                lastExpanded = -1
            } else {
                lastExpanded = -1
                expanded[seq] = 0
                $(clicked).animate({ 'height': keyHeights[seq] }, 320, function () {
                    $(clicked).find('.det-info').hide()
                })
            }
        }, timeoutLength); // run donothing after 0.5 seconds
    })
}

function calcDist(lon1, lat1, lon2, lat2) {
    lat1 = lat1 * Math.PI / 180
    lat2 = lat2 * Math.PI / 180
    lon1 = lon1 * Math.PI / 180
    lon2 = lon2 * Math.PI / 180

    dlat = Math.abs(lat1 - lat2)
    dlon = Math.abs(lon1 - lon2)
    ac = Math.sqrt((Math.sin(dlat / 2)) ** 2 + Math.cos(lat1) * Math.cos(lat2) * ((Math.sin(dlon / 2)) ** 2))
    c = 2 * Math.atan2(ac, Math.sqrt(1 - ac ** 2))
    dist = 6356 * c

    return dist
}

var hospitalGrp = []
var specs1 = []
var coords1 = []
var coords2 = []
function loadPoints() {
    if (map.hasLayer(hospitalCont)) { hospitalCont.removeFrom(map) }
    hospitalLayer1.redraw()

    hospitalGrp = []
    specs1 = []
    specs1 = []
    markersLtd1 = []; markersInc1 = []
    // addHospitals('', excluded, '#777', '#333', '#bbb', hospitalGrp)
    addHospitals('ltd1', limited, '#e81', '#e10', '#fa1', hospitalGrp)
    addHospitals('inc1', included, '#2f5', '#ff0', '#2f5', hospitalGrp)

    $('.src-lookup-prompt-circle')
        .off('mouseover')
        .on('mouseover', function () {
            $(this).attr('opacity', 1)
        })
        .off('mouseout')
        .on('mouseout', function () {
            $(this).attr('opacity', 0)
        })
    hospitalCont = L.layerGroup(hospitalGrp)
    hospitalCont.addTo(map)

    geoPosList()

}

function loadPlace(canvasOverlay, info) {
    console.log('loading--')
    var zoom = map.getZoom()
    var ctx = info.canvas.getContext('2d');
    ctx.clearRect(0, 0, info.canvas.width, info.canvas.height);
    $('#map > div.leaflet-pane.leaflet-map-pane > div.leaflet-pane.leaflet-overlay-pane > canvas').css('z-index', '2500')

    for (var i = 0; i < places.length; i++) {
        if (zoom < 8 && places[i]['admin-level'] == 'city') {
            // load province stats layer
            lon = places[i]['centroid'][0]
            lat = places[i]['centroid'][1]

            if (info.bounds.contains([lat, lon])) {
                dot = map.latLngToContainerPoint([lat, lon]);

                ctx.beginPath()
                ctx.fillStyle = "rgba(200,200,200, 0.50)";
                ctx.fillRect(dot.x - 25, dot.y - 10, 50, 20)
                ctx.closePath()

                ctx.beginPath()
                ctx.font = '14px bold serif';
                ctx.fillStyle = '#000'
                ctx.fillText(places[i]['city'], dot.x - 25, dot.y + 5)
                ctx.closePath()
            }
        } else if (zoom >= 8 && places[i]['admin-level'] == 'city-district') {
            // load province stats layer
            lon = places[i]['centroid'][0]
            lat = places[i]['centroid'][1]

            if (info.bounds.contains([lat, lon])) {
                dot = map.latLngToContainerPoint([lat, lon]);

                ctx.beginPath()
                ctx.fillStyle = "rgba(200,200,200, 0.50)";
                ctx.fillRect(dot.x - 25, dot.y - 20, 50, 40)
                ctx.closePath()

                ctx.beginPath()
                ctx.font = '14px bold serif';

                ctx.fillStyle = '#000'
                ctx.fillText(places[i]['city'], dot.x - 25, dot.y - 4)

                ctx.font = '12px serif';
                ctx.fillText(places[i]['district'], dot.x - 25, dot.y + 12)

                ctx.closePath()
            }
        }
    }
}

function updatePlaceLayer() {
    placeLayer.drawing(loadPlace)
    placeLayer.redraw()
}

function updateHospitalLayer1() {
    hospitalLayer1.drawing(loadHospitals1)
    hospitalLayer1.redraw()
}

function updateHospitalLayer2() {
    hospitalLayer2.drawing(loadHospitals2)
    hospitalLayer2.redraw()
}

(function () {
    // $('.service').hide()
    map = initMap()
    $('.leaflet-pane.leaflet-marker-pane').css('z-index', '400')
    $('#show-label').prop('checked', true)

    placeLayer = L.canvasOverlay().addTo(map)
    hospitalLayer1 = L.canvasOverlay().addTo(map)
    hospitalLayer2 = L.canvasOverlay().addTo(map)

    $.getJSON('data/hubei3.geojson', function (result) {
        for (i = 0; i < result['features'].length; i++) {
            places.push(result['features'][i]['properties'])
        }

        updatePlaceLayer()

        L.geoJson(result, {
            style: function (feature) {
                if ((feature['properties']['admin-level'] == 'city')) {
                    return ({
                        'opacity': 0,
                        "fillColor": "#000000",
                        "fillOpacity": '0.35',
                    })
                }
            },
            filter: function (feature) {
                if (feature['properties']['admin-level'] == 'city') {
                    return true
                }
            }
        }).addTo(map)
        L.geoJson(result, {
            style: function (feature) {
                if ((feature['properties']['admin-level'] == 'city-district')) {
                    return ({
                        "color": "#e4c2c2",
                        "fillColor": "#000000",
                        "fillOpacity": '0',
                        "weight": 1.5
                    })
                }
            },
            filter: function (feature) {
                if (feature['properties']['admin-level'] == 'city-district') {
                    return true
                }
            }
        }).addTo(map)

        L.geoJson(result, {
            style: function (feature) {
                if ((feature['properties']['admin-level'] == 'city')) {
                    return ({
                        "color": "#e8e810",
                        "fillColor": "#000000",
                        "fillOpacity": '0',
                        "weight": 4
                    })
                }
            },
            filter: function (feature) {
                if (feature['properties']['admin-level'] == 'city') {
                    return true
                }
            }
        }).addTo(map)
    })

    var promises = []
    navigator.geolocation.getCurrentPosition(gotPos, errPos)
    promises.push($.getJSON('data/gh10.json'))
    promises.push($.getJSON('data/hubei22.json'))
    promises.push($.getJSON('data/wuhan_dialysis.json'))
    promises.push($.getJSON('data/wuhan_tumor.json'))
    promises.push($.getJSON('data/wuhan_emergency.json'))
    // promises.push($.getJSON('data/hubei_official.json'))
    // promises.push(curPos)
    Promise.all(promises).then(prep_hospitals)

})()